#include "RspTransmition.h"

extern UART_HandleTypeDef huart4;
extern DMA_HandleTypeDef hdma_uart4_rx;
extern DMA_HandleTypeDef hdma_uart4_tx;
uint8_t isFreeRTOSSyson = 0;
//extern osMessageQueueId_t RspReceiveQueueHandle;
extern osSemaphoreId Uart_Recv_BinarySemHandle;

USART_RECEIVETYPE UART4Reciever;

void DigitalOutput(uint8_t InputDigital)
{
    uint8_t mylength[20] = "";
    
    if(InputDigital == 0)
    {
        mylength[0]= InputDigital % 10 + '0';
        HAL_UART_Transmit_DMA(&huart4,(uint8_t*)mylength,1);
        HAL_UART_Transmit_DMA(&huart4,(uint8_t*)" ",1);
    }
    while(InputDigital > 0)
    {
        mylength[0]= InputDigital % 10 + '0';
        HAL_UART_Transmit_DMA(&huart4,(uint8_t*)mylength,1);
        osDelay(10);
        InputDigital /= 10;   
    }
    HAL_UART_Transmit_DMA(&huart4,(uint8_t*)"\n",1);
}


char BufferReceive[100];

void RSPTransmitInitStart()
{
    // __enable_irq();   
    // 启用空闲中断
    __HAL_UART_ENABLE_IT(&huart4, UART_IT_IDLE);
    // 使能DMA传输完成中断
    __HAL_DMA_ENABLE_IT(&hdma_uart4_tx, DMA_IT_TC);
    // 启动DMA接收
    HAL_UART_Receive_DMA(&huart4,(uint8_t*)BufferReceive,UART4_BUFF_SIZE);
}


uint8_t Rxlen = 0;
// receive Comand string from DMA and send it to the queue
// 读取串口DMA中接收Rsp发来的指令字符串并转发到信息队列中
void RspUART4ReceiveIDLEFromISR() //中断不能延时
{
    if(__HAL_UART_GET_FLAG(&huart4, UART_FLAG_IDLE) != RESET) {
        __HAL_UART_CLEAR_IDLEFLAG(&huart4);
        
        // 停止 DMA 接收
        HAL_UART_DMAStop(&huart4);
        
        // 计算接收长度
        Rxlen = __HAL_DMA_GET_COUNTER(&hdma_uart4_rx);

        BaseType_t xHigherPriorityTaskWoken = pdFALSE;
        xSemaphoreGiveFromISR(Uart_Recv_BinarySemHandle, &xHigherPriorityTaskWoken);
        portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
    }
}

void RspReceivedOperation()
{
    if(xSemaphoreTake(Uart_Recv_BinarySemHandle, 0) == pdTRUE) {  
        HAL_UART_Transmit_DMA(&huart4,(uint8_t*)BufferReceive,Rxlen);
        HAL_UART_Transmit_DMA(&huart4,(uint8_t*)"\n",1);
        osDelay(20);
        
        GetCommandAndPerform(BufferReceive);
        osDelay(20);
        
        Rxlen = 0;
        memset(BufferReceive,0,sizeof(BufferReceive));
        HAL_UART_Receive_DMA(&huart4, (uint8_t*)BufferReceive, UART4_BUFF_SIZE);
    }
}
